package com.dily.study.demo.config.websocket.second;

/**
 * Date: 2022-05-12 星期四
 * Time: 15:54
 * Author: Dily_Su
 * Remark: 相当于Controller
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/ws")
@RestController
public class TestWebSocket {

    // 用来记录当前连接数的变量
    private static volatile int onlineCount = 0;

    // concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象
    private static final CopyOnWriteArraySet<TestWebSocket> webSocketSet = new CopyOnWriteArraySet<>();

    // 与某个客户端的连接会话，需要通过它来与客户端进行数据收发
    private Session session;

    private static final Logger LOGGER = LoggerFactory.getLogger(TestWebSocket.class);

    /**
     * 打开连接
     *
     * @param session 会话
     * @throws Exception 异常
     */
    @OnOpen
    public void onOpen(Session session) throws Exception {
        this.session = session;
        webSocketSet.add(this);
    }

    /**
     * 关闭连接
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
    }

    /**
     * 接收消息
     *
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session) throws Exception {
        System.out.println(message);
        sendMessage("哈喽你好，我收到你的消息我就来了");
    }

    /**
     * 报错
     *
     * @param session 会话
     * @param error   错误
     */
    @OnError
    public void onError(Session session, Throwable error) {
    }

    /**
     * 发送消息
     *
     * @param message 会话
     * @throws Exception 异常
     */
    public void sendMessage(String message) throws Exception {
        if (this.session.isOpen()) {
            this.session.getBasicRemote().sendText(message);
        }
    }

    /**
     * 获取在线连接数
     *
     * @return onlineCount
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    /**
     * 增加在线数量
     */
    public static synchronized void addOnlineCount() {
        TestWebSocket.onlineCount++;
    }

    /**
     * 减少在线数量
     */
    public static synchronized void subOnlineCount() {
        TestWebSocket.onlineCount--;
    }
}